import React, { useState, useEffect } from 'react';
import { uDb, cline, ErrView, Wait, BaseDlg, NuiBt } from 'sui';
import { g_db } from 'db/state';
import { loc } from 'local';
import { Scan, Pcode} from './ctl';
import { init_info } from 'use/info';

const DlgFree = ({ open, setOpen, umd }) => {
    const [fin, setFin] = useState("scan");
    const [err, setErr] = useState("");
    const [wait, setWait] = useState(false);

    useEffect(() => {
        if (!open) {
            return;
        }

        setErr("");

        g_db.stop_scan();
    }, [open]);

    const hok = (sn) => {
        setWait(true);

        const herr = (e) => {
            setErr(e);
            setWait(false);
        };

        uDb(null, `file/rm/box_${g_db.box()}`,
            {
                line: cline(),
                sn: sn,
            },
            () => uDb(null, `file/list/box_${g_db.box()}`, { line: cline() },
                r => {
                    const box = [];

                    r.forEach(d => {
                        if (d.sn === "attr") {
                            return;
                        }

                        box.push(d);
                    });

                    init_info(box);

                    const c = box.length;

                    umd.set("sum", c);
                    g_db.s_sum(c);

                    setWait(false);
                    setOpen(false);
                },
                e => {
                    init_info(null);
                    umd.set("sum", 0);
                    g_db.s_sum(0);

                    setWait(false);
                }
            ), e => herr("解绑轴承出错"));
    };

    const getView = () => {
        if (fin === "scan") {
            return <Scan hcmd={hok} open={open} setOpen={setOpen} lok="解绑"/>;
        }

        return <Pcode hcmd={hok} open={open} setOpen={setOpen} lok="解绑"/>;
    };

    return (
        <BaseDlg open={open} title="解绑轴承">
            <div className="flex flex-col">
                <ErrView err={err}/>
                <div className="flex flex-row ml-4">
                    <NuiBt color={fin === "scan" ? "green": "blue"} hcmd={() => setFin("scan")}>{loc("base_62")}</NuiBt>
                    <NuiBt className="ml-4" color={fin === "scan" ? "blue": "green"} hcmd={() => setFin("pass")}>{loc("base_59")}</NuiBt>
                </div>
                {getView()}
                <Wait wait={wait}/>
            </div>
        </BaseDlg>
    );
};

export {DlgFree};
